//


const express = require("express");//得到一个express对象
const router = express.Router();
const db = require("../model/db");
const crypto = require("crypto");//引用加密模块

/**
 * 添加用户
 */
router.post("/", async (req, res) => {
  const md5 = crypto.createHash("md5");//使用MD5算法创建hash加密对象
  const data = await db.Users.create({
    pwd: md5.update(req.body.pwd).digest("hex"),
    loginname: req.body.loginname,
    username: req.body.username,
    mobile: req.body.mobile,
    role: req.body.role,
    email: req.body.email,
    status: req.body.status,
  });
  res.send({
    code: 0,
    message: "",
    data
  });
})



/**
 * 查询所有用户
 */
router.get("/", async (req, res) => {

  if (!req.query.field) {//默认按照id排序
    req.query.field = "_id";

  }
  if (!req.query.sort) {//默认按照升序排序
    req.query.sort = "asc";
  }
  //拼接排序字符串
  let s = req.query.field;
  if (req.query.sort === "desc") {
    s = "-" + s;
  }

  //处理分页
  if (!req.query.page) {
    req.query.page == 1;//页索引默认为1
  }
  if (!req.query.limit) {
    req.query.limit == 10;//页容量 默认为10
  }
  const page = parseInt(req.query.page);
  const limit = parseInt(req.query.limit);

  let condition = {};
  if (req.query.key) {
    const exp = new RegExp(req.query.key, "i") //不区分大小写
    condition = {
      $or: [
        { loginname: { $regex: exp } },
        { username: { $regex: exp } },
        { status: { $regex: exp } },
        { mobile: { $regex: exp } },
        { name: { $regex: exp } },
        { role: { $regex: exp } },
        { email: { $regex: exp } }
      ]
    };
  }
  const data = await db.Users.find(condition).sort(s).skip((page - 1) * limit).limit(limit);//升序降序 
  const count = await db.Users.countDocuments(condition);
  res.send({
    code: 0,
    message: "",
    count,
    data
  });
})

/**
 * 删除用户
 */
router.delete("/:id", async (req, res) => {
  console.log(req.params)
  await db.Users.deleteOne({//条件对象
    _id: db.ObjectId(req.params.id),//类型转换
  })
  res.send({
    "code": 0,
    "message": "删除成功"
  });
})
/** 
 * 修改用户 
 **/
router.put("/:id", async (req, res) => {
  console.log(req.body)
  await db.Users.updateOne({//条件对象
    _id: req.params.id
  }, req.body)
  res.send({
    "code": 0,
    "message": "修改成功",
    "data": req.body
  });
})

/**
 * 单个查询
 */
router.get("/:id", async (req, res) => {
  const data = await db.Users.findById(req.params.id)
  res.send(data);
})


/**
 * 验证
 */
router.post("/login", async (req, res) => {

  const md5 = crypto.createHash("md5");//使用MD5算法创建hash加密对象

  // 根据传递的账号密码，从数据库中匹配用户，如果找到用户，将用户对象响应，如果没有找到，响应false
  const data = await db.Users.findOne({ mobile: req.body.mobile, pwd: md5.update(`${req.body.pwd}`).digest("hex"), });
  // const data = await db.Users.findOne({ loginname: req.body.loginname, pwd: md5.update(`${req.body.pwd}`).digest("hex"), });

  if (data != null && data.status === "available") {
    //响应的结果中包含cookie
    res.cookie("userId", "wpxwpx", {
      maxAge: 7 * 24 * 60 * 60 * 1000,//有效期
      // signed: true
    })
    // res.send(true);  
    res.send(data);
    return;
  }
  res.send(false);

})



/**
 * 登陆权限
 */
router.get("/login/:id", async (req, res) => {
  const data = await db.Users.findById(req.params.id);
  // 超管1 门店2 供应商3
  if (data.role === "超管" && data.status === "available") {
    res.send({
      "message": "true" + data.role,
      "data": 1
    });
    return;
  }
  else if (data.role === "门店" && data.status === "available") {
    res.send({
      "message": "true" + data.role,
      "data": 2
    });
    return;
  }
  else if (data.role === "供应商" && data.status === "available") {
    res.send({
      "message": "true" + data.role,
      "data": 3
    });
    return;
  }
  res.send(false);
})

module.exports = router;
